package handlers

import (
	"capsule-stay/models"
	"github.com/gin-gonic/gin"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	author := c.PostForm("author")
	content := c.PostForm("content")
	like, _ := strconv.Atoi(c.PostForm("like"))
	collection, _ := strconv.Atoi(c.PostForm("collection"))
	if title == "" || author == "" || content == "" || like == 0 || collection == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "内容不能为空",
		})
		return
	}
	data := models.Article{
		Title:      title,
		Author:     author,
		Content:    content,
		Like:       like,
		Collection: collection,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var article models.Article
	err := models.DB.Where("id=?", id).First(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": article,
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))

	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))

	Offset := (page - 1) * size

	query := models.DB.Model(&models.Article{})

	var count int64
	query.Count(&count)
	var list []models.Article
	err := query.Offset(Offset).Limit(size).Find(&list).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": gin.H{
			"count": count,
			"list":  list,
		},
	})
	return
}
